package com.test23_正则表达式;

import org.junit.Test;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Demo03_Test {

    @Test
    public void test1() {
        // 字符串替换，通过正则只保留小写字母
        String str = "yo@@@@otUUUk.c###om";
        String regex = "[^a-z]";
        System.out.println(str.replaceAll(regex, ""));
    }

    @Test
    public void test2() {
        // 字符串拆分
        String str = "yootk.com137edu.yootk.com24068yootk.ke.qq.com";
        String regex = "\\d+";
        String[] result = str.split(regex);
        for (String temp : result) {
            System.out.println(temp);
        }
    }

    @Test
    public void test3() {
        // 安全的数值转换
        String str = "789a456";
        String regex = "\\d+";
        if (str.matches(regex)) {
            System.out.println("【字符串转换数字】" + Integer.parseInt(str));
        } else {
            System.out.println("【ERROR】当前字符串不符合正则规则！");
        }
    }

    @Test
    public void test4() {
        ZoneId zoneId = ZoneId.systemDefault();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 正则匹配并且实现日期转换
        String str = "1998-08-19 20:34:59";
        String dateRegex = "\\d{4}-\\d{2}-\\d{2}";
        String datetimeRegex = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}";
        if (str.matches(dateRegex)) {
            LocalDate localDate = LocalDate.parse(str, dateFormatter);
            Instant instant = localDate.atStartOfDay(zoneId).toInstant();
            Date date = Date.from(instant);
            System.out.println("【字符串转日期】" + date);
        } else if (str.matches(datetimeRegex)) {
            LocalDateTime localDatetime = LocalDateTime.parse(str, datetimeFormatter);
            Instant instant = localDatetime.atZone(zoneId).toInstant();
            Date date = Date.from(instant);
            System.out.println("【字符串转日期时间】" + date);
        }
    }

    @Test
    public void test5() {
        // 正则匹配电话号码
        // String str = "18812345678";
        // String str = "+8618812345678";
        String str = "008618812345678";
        String regex = "((\\+|00)\\d{2})?\\d{11}";
        System.out.println(str.matches(regex));
    }

    @Test
    public void test6() {
        // 正则匹配email
        String str = "muyan.yootk-lixinghua@yootk.com";
        // 用户名：[a-zA-Z_][a-zA-Z0-9\-_\.]+
        // 固定字符：@
        // 域名：[a-zA-Z0-9\-]+
        // 结尾：\.(com|com\.cn|net|net\.cn|gov|edu)
        StringBuilder regex = new StringBuilder();
        regex.append("[a-zA-Z_][a-zA-Z0-9\\-_\\.]+");
        regex.append("@");
        regex.append("[a-zA-Z0-9\\-]+");
        regex.append("\\.(com|com\\.cn|net|net\\.cn|gov|edu)");
        System.out.println(str.matches(regex.toString()));
    }
}
